package com.jacken.mars.entity.base;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

/**
 * 基础controller
 *
 * @author wq
 * @date 2019/12/6
 **/
@Slf4j
public abstract class AbstractBasicController {


    public HttpServletRequest request;

    public HttpServletResponse response;

    /**
     * 封装参数 (每次执行方法前都会先调用该方法封装)
     *
     * @param request  response
     * @param response response
     */
    @ModelAttribute
    public void getReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }

    /**
     * 获取IP地址
     *
     * @return IP
     */
    public String getIp() {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.contains(",")) {
            String[] split = ip.split(",");
            return split[0];
        }
        return ip;
    }


    /**
     * 获取分页对象
     *
     * @return 分页
     */
    public <T> Page<T> getPage() {
        String currentPage = request.getParameter("pageNumber");
        String pageSize = request.getParameter("pageSize");
        int page = 1;
        int size = 10;

        if (!StringUtils.isEmpty(currentPage)) {
            page = Integer.parseInt(currentPage);
        }

        if (!StringUtils.isEmpty(pageSize)) {
            size = Integer.parseInt(pageSize);
        }

        return new Page<>(page, size);
    }

    /**
     * 获取当前用户ID
     *
     * @return getUserId
     */
    public abstract Integer getUserId();

    /**
     * 获取token
     *
     * @return token
     */
    public String getToken() {
        String authorization = request.getHeader("token");
        if (StringUtils.isEmpty(authorization)) {
            return request.getParameter("token");
        }
        return authorization;
    }

}
